package fr.utbm.lo53;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.InterfaceAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

public class Network {
	public static String getMacByIp(String ip) {
		String fichier = "/proc/net/arp";
		int nbLine = 0;
		String mac = null;
		try{
			InputStream ips=new FileInputStream(fichier); 
			InputStreamReader ipsr=new InputStreamReader(ips);
			BufferedReader br=new BufferedReader(ipsr);
			String ligne;
			while ((ligne=br.readLine())!=null){
				if (nbLine != 0) {
					String[] col = ligne.split(" +");
					System.out.println(col[3]);
					if (col[0].equals(ip))
						mac = col[3];
				}
				nbLine++;
			}
			br.close(); 
		}		
		catch (Exception e){
			System.out.println(e.toString());
		}
		return mac;
	}
	public static InetAddress getBroadcastAddr() throws SocketException {
		InetAddress broadcast = null;
		Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
			while (interfaces.hasMoreElements()) {
			  NetworkInterface networkInterface = interfaces.nextElement();
			  if (networkInterface.isLoopback())
			    continue;    // Don't want to broadcast to the loopback interface
			  for (InterfaceAddress interfaceAddress :
			    networkInterface.getInterfaceAddresses()) {
			    broadcast = interfaceAddress.getBroadcast();
			    if (broadcast == null)
			      continue;
			    // Use the address
			  }
			}
		return broadcast;
	}
}
